﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace SimpleX
{
    public static partial class ServicesExtension
    {
        public static IServiceCollection AddControllers(this IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.Filters.Add<UnifyResultFilter>();

                var actionFilters = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IAsyncActionFilter))));

                foreach (var item in actionFilters)
                    options.Filters.Add(item);
            })
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new JsonIgnoreAttributeContractResolver();// DefaultContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                options.SerializerSettings.NullValueHandling = NullValueHandling.Include;

                //预防磁盘IO高的问题
                //https://www.cnblogs.com/lizhenghao126/articles/17061154.html
                options.InputFormatterMemoryBufferThreshold = 1024 * 1024;
                options.OutputFormatterMemoryBufferThreshold = 1024 * 1024;
            });
            //.AddJsonOptions(options =>
            //{
            //    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            //    options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
            //    options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals | JsonNumberHandling.AllowReadingFromString;// | JsonNumberHandling.WriteAsString;
            //    options.JsonSerializerOptions.WriteIndented = true;
            //});

            services.AddRouting(options => options.LowercaseUrls = true);

            return services;
        }
    }
}